package com.zzyl.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.service.WeChatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class WeChatServiceImpl implements WeChatService {
    // 登录
    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    @Value("${zzyl.framework.wechat.appId}")
    private String appId;

    @Value("${zzyl.framework.wechat.appSecret}")
    private String secret;

    /**
     * 封装公共参数
     * @return
     */
    private Map<String, Object> getAppConfig() {

        Map<String, Object> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid",appId);
        requestUrlParam.put("secret",secret);
        return requestUrlParam;
    }
    @Override
    public String getOpenId(String code) throws IOException  {
        //封装参数
        Map<String,Object> requestUrlParam = getAppConfig();
        requestUrlParam.put("js_code",code);

        String result = HttpUtil.get(REQUEST_URL, requestUrlParam);

        JSONObject jsonObject = JSONUtil.parseObj(result);
        // 若code不正确，则获取不到openid，响应失败
        if (ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))) {
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }

        return jsonObject.getStr("openid");
    }

    @Override
    public String getPhone(String detailCode) {
        String token=getToken();
        String url =PHONE_REQUEST_URL.concat(token);
        HashMap<String,Object>map =new HashMap<>();
        map.put("code",detailCode);

        String result =HttpUtil.post(url,JSONUtil.toJsonStr(map));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if(jsonObject.getInt("errcode")!=0){
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }
    public String getToken(){
        Map<String,Object>map =getAppConfig();
        String result =HttpUtil.get(TOKEN_URL,map);
        JSONObject jsonObject=JSONUtil.parseObj(result);
        if(!ObjectUtil.isEmpty(jsonObject.getInt("errcode"))){
            throw new RuntimeException(jsonObject.getStr("errmsg"));
        }
        String accessToken= jsonObject.getStr("access_token");
        return  accessToken;
    }

}
